package com.khyr.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khyr.Dao.*;
import com.khyr.Service.ChargeService;
import com.khyr.entity.*;
import com.khyr.feign.DictTypeFeign;
import com.khyr.feign.UserFeign;
import com.khyr.utils.SnowflakeIdGenerator;
import com.khyr.vo.OrderChargeRequestVo;
import com.khyr.vo.PrescriptionChargeVo;
import com.khyr.vo.QueryParamsVo;
import com.khyr.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：lyk
 * @date ：Created in 2025/3/11 16:04
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class ChargeServiceImpl implements ChargeService {
    @Autowired
    private CareHistoryDao careHistoryDao ;
    @Autowired
    private CareOrdersDao careOrdersDao;
    @Autowired
    private DictTypeFeign dictTypeFeign;
    @Autowired
    private HisOrderChargeDao hisOrderChargeDao;
    @Autowired
    private HisOrderChargeItemDao hisOrderChargeItemDao;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CareOrderItemDao careOrderItemDao;
    @Autowired
    private HisRegistrationDao hisRegistrationDao;

    @Override
    public R<PrescriptionChargeVo> getNoChargeCareHistoryByRegId(String regId) {
        try {
            PrescriptionChargeVo prescriptionChargeVo = new PrescriptionChargeVo();
            // 从挂号表获取患者ID
            QueryWrapper<HisRegistration> registrationQueryWrapper = new QueryWrapper<>();
            registrationQueryWrapper.eq("registration_id", regId);
            HisRegistration registration = hisRegistrationDao.selectOne(registrationQueryWrapper);
            if (registration == null) {
                return new R<>(500, "未找到挂号信息", null);
            }
            
            // 从病历表获取病历信息
            QueryWrapper<CareHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("reg_id", regId);
            CareHistory careHistory = careHistoryDao.selectOne(queryWrapper);
            
            // 获取未收费的处方信息
            List<CareOrder> careOrders = careOrdersDao.getCareOrdersByPatientId(registration.getPatientId());
            
            prescriptionChargeVo.setCareHistory(careHistory);
            prescriptionChargeVo.setCareOrders(careOrders);
            return new R<>(200, "数据获取成功", prescriptionChargeVo);
        } catch (Exception e) {
            return new R<>(500, "数据获取失败", null);
        }
    }

    @Override
    public R<List<DictData>> dictionary(String dictType) {
        return dictTypeFeign.getDictDataByType(dictType);
    }

    @Override
    public R<String> createOrderChargeWithCash(OrderChargeRequestVo orderChargeRequestVo) {
        // 获取订单信息
        HisOrderCharge hisOrderCharge = orderChargeRequestVo.getOrderChargeDto();
        hisOrderCharge.setOrderId("ODC"+ SnowflakeIdGenerator.nextId());
        hisOrderCharge.setOrderStatus(String.valueOf(1));
        hisOrderCharge.setPayType(String.valueOf(0));
        String token = request.getHeader("token");
        hisOrderCharge.setCreateBy(userFeign.getUserInfo(token).getData().getUserName());
        hisOrderCharge.setCreateTime(new Date());
        hisOrderCharge.setPayTime(new Date());
        hisOrderCharge.setUpdateTime(new Date());
        int i=hisOrderChargeDao.insert(hisOrderCharge);
        // 获取订单项列表
        List<HisOrderChargeItem> hisOrderChargeItemList = orderChargeRequestVo.getOrderChargeItemDtoList();
        List<String> ItemIdList = new ArrayList<>();
        for (HisOrderChargeItem item : hisOrderChargeItemList) {
            if (hisOrderChargeItemDao.selectById(item.getItemId())==null){
                item.setOrderId(hisOrderCharge.getOrderId());
                item.setStatus(String.valueOf(1));
                hisOrderChargeItemDao.insert(item);
                ItemIdList.add(item.getItemId());
            }
        }
        if (!ItemIdList.isEmpty()){
            hisOrderChargeItemDao.updateBatchById(ItemIdList);
        }
        // 返回成功结果
        if (i>0){
            return new R<>(200,"订单创建成功",null);
        }else{
            return new R<>(500,"订单创建失败",null);
        }
    }
    @Override
    public R<String> payWithCash(String orderId) {
        QueryWrapper<HisOrderChargeItem> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<HisOrderChargeItem> hisOrderChargeItems = hisOrderChargeItemDao.selectList(queryWrapper);
        for (HisOrderChargeItem item : hisOrderChargeItems) {
            CareOrderItem careOrderItem = careOrderItemDao.selectById(item.getItemId());
            careOrderItem.setStatus("1");
            careOrderItemDao.updateById(careOrderItem);
            item.setStatus(String.valueOf(1));
            hisOrderChargeItemDao.updateById(item);
        }
        HisOrderCharge hisOrderCharge = hisOrderChargeDao.selectById(orderId);
        hisOrderCharge.setOrderStatus(String.valueOf(1));
        hisOrderCharge.setPayType(String.valueOf(0));
        String token = request.getHeader("token");
        hisOrderCharge.setUpdateBy(userFeign.getUserInfo(token).getData().getUserName());
        hisOrderCharge.setUpdateTime(new Date());
        hisOrderChargeDao.updateById(hisOrderCharge);
        if (hisOrderChargeDao.updateById(hisOrderCharge)>0) {
            return new R<>(200, "订单支付成功", null);
        }else {
            return new R<>(500, "订单支付失败", null);
        }
    }

    @Override
    public  R<Page<HisOrderCharge>> queryAllOrderChargeForPage(QueryParamsVo queryParamsVo) {
        QueryWrapper<HisOrderCharge> queryWrapper=new QueryWrapper<>();
        // 根据 noticeVo 中的条件动态构建查询条件
        if (queryParamsVo.getRegId() != null) {
            queryWrapper.like("reg_id", queryParamsVo.getRegId());
        }
        if(StringUtils.hasText(queryParamsVo.getPatientName())){
            queryWrapper.like("patient_name", queryParamsVo.getPatientName());
        }
        if(queryParamsVo.getPageNum()!=null&&queryParamsVo.getPageSize()!=null){
            Page<HisOrderCharge> page = new Page<>(queryParamsVo.getPageNum(), queryParamsVo.getPageSize());
            Page<HisOrderCharge> p = hisOrderChargeDao.selectPage(page, queryWrapper);
            return new R<>(200,"查询成功",p);
        }else{
            return new R<>(500,"查询失败",null);
        }
    }
    @Override
    public R<List<HisOrderChargeItem>> queryOrderChargeItemByOrderId(String orderId) {
        QueryWrapper< HisOrderChargeItem> queryWrapper=new QueryWrapper<>();
        // 根据 noticeVo 中的条件动态构建查询条件
        queryWrapper.like("order_id", orderId);
        List<HisOrderChargeItem> hisOrderChargeItems = hisOrderChargeItemDao.selectList(queryWrapper);
        if (hisOrderChargeItems!=null){
            return new R<>(200,"查询成功",hisOrderChargeItems);
        }else {
            return new R<>(500,"查询失败",null);
        }
    }

    @Override
    public R<List<CareOrder>> getCareOrderByRegId(String regId) {
        QueryWrapper<CareOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("ch_id", regId);
        List<CareOrder> careOrders = careOrdersDao.selectList(queryWrapper);
        if (careOrders.isEmpty()){
            return new R<>(500,"查询失败",null);
        }
        return new R<>(200,"查询成功",careOrders);
    }
}